<template>
    <a-modal v-model:visible="visible" :title="title" :mask-closable="false" :esc-to-close="false"
        :modal-style="{ maxWidth: '1000px' }" width="90%" @before-ok="save" @close="reset">
        <a-form ref="formRef" :model="form" :rules="rules" size="large" auto-label-width>
            <a-form-item label="标题" field="title">
                <a-input placeholder="请输入标题" v-model.trim="form.title"></a-input>
            </a-form-item>
            <div style="flex: 1;">
                <AiEditor v-model="form.content" />
            </div>
        </a-form>

    </a-modal>
</template>
  
<script setup lang="ts">
import { addCompanyIntroduction, getCompanyIntroduction, updateCompanyIntroduction } from '@/apis/website';
import { useForm } from '@/hooks';
import { Message, type FormInstance } from '@arco-design/web-vue';
import AiEditor from './components/edit/index.vue';

const visible = ref(false)
const dataId = ref('')
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改简介' : '新增简介'))

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const formRef = ref<FormInstance>()
const { form, resetForm } = useForm({
    companyId: undefined
})

const rules: FormInstance['rules'] = {
    title: [{ required: true, message: '请输入标题' }],
    content: [{ required: true, message: '请输入内容' }],
}

// 重置
const reset = () => {
    formRef.value?.resetFields()
    resetForm()
}

// 新增
const onAdd = (id?: string, companyId?: string) => {
    reset()

    dataId.value = ''

    form.companyId = companyId

    visible.value = true
}

// 修改
const onUpdate = async (id: string) => {
    reset()

    dataId.value = id

    const res = await getCompanyIntroduction(id)
    Object.assign(form, res.data)

    visible.value = true
}

// 保存
const save = async () => {
    const isInvalid = await formRef.value?.validate()
    if (isInvalid) return false

    if (isUpdate.value) {
        await updateCompanyIntroduction(form, dataId.value)
        Message.success('修改成功')
    } else {
        await addCompanyIntroduction(form)
        Message.success('新增成功')
    }

    emit('save-success')
}

defineExpose({ onAdd, onUpdate })
</script>

<style lang="scss" scoped></style>
  